const fs = require('fs');
const path = require('path');
const resolve = require('resolve');
function resolvePlugin({ root }) {
  return {
    name: 'vite:resolve',
    resolveId(id, importer) {
      //如果/开头表示是绝对路径
      if (id.startsWith('/')) {
        return { id: path.resolve(root, id.slice(1)) }; //  /main.js ---> F:\<currentProjectPath>\main.js
      }
      //如果是绝对路径 C:\...
      if (path.isAbsolute(id)) {
        return { id }
      }
      //如果是相对路径
      if (id.startsWith('.')) {
        const basedir = path.dirname(importer);
        const fsPath = path.resolve(basedir, id)
        return { id: fsPath };
      }
      //如果是第三方包 ---> import vue from 'vue'
      let res = tryNodeResolve(id, importer, { root });
      if (res) {
        return res;
      }
    }
  }
}

function tryNodeResolve(id, importer, config) {
  //https://www.npmjs.com/package/resolve
  //同步解析模块路径字符串id，返回结果并在id无法解析时抛出错误。
  const pkgPath = resolve.sync(`${id}/package.json`, {basedir: config.root })
  const pkgDir = path.dirname(pkgPath);
  const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
  const entryPoint = pkg.module; //package.json中的module字段指定的值作为esmodule的查找入口
  const entryPointPath = path.join(pkgDir, entryPoint);
  return {id: entryPointPath};
}

module.exports = resolvePlugin;
